# coding:utf-8
"""
    进程通信
        依赖队列
    通信方法


    Queue 队列的创建 mac_cout 队列对象

    put 信息放入队列 message 无返回
    get 获取队列信息 无        str

"""
import json
import logging
import multiprocessing
import time
from multiprocessing import Queue


class Worker(object):
    def __init__(self, queue):
        self.queue = queue

    def send(self, message):
        if not isinstance(message, str):
            message = json.dumps(message)
        self.queue.put(message)

    def receive(self):
        while True:
            result = self.queue.get()
            try:
                res = json.loads(result)
                if res == 'Exit':
                    break
                print('recv is %s' % res)
            except:
                logging.error('错误消息格式: %s' % result)

    def send_all(self):
        for i in range(10):
            self.queue.put(json.dumps(i))
            time.sleep(1)

    def send_exit(self):
        self.queue.put(json.dumps('Exit'))

if __name__ == '__main__':
    q = multiprocessing.Queue()
    work = Worker(q)
    send = multiprocessing.Process(target=work.send, args=({'name': 'yeskip'},))
    send_all = multiprocessing.Process(target=work.send_all)

    receive = multiprocessing.Process(target=work.receive)
    send_all.start()
    send.start()
    receive.start()

    send_all.join()
    work.send_exit()
    # receive.terminate()